using System;
using System.Collections;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Web;
using System.Web.Caching;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;
using WebPart=Microsoft.SharePoint.WebPartPages.WebPart;

namespace zevenseas.Community.Web.UI.WebControls.WebParts
{
    public class zsWebPart : WebPart
    {
        private bool inError = false;
        private bool renderToIndexer = true;
        private Collection<zsWebPartException> errors;
        private bool debugMode = false;

        [WebBrowsable(true), WebDisplayName("Debug Mode")]
        [Personalizable(PersonalizationScope.Shared), SPWebCategoryName("Debugging"), DefaultValue(false)]
        public bool DebugMode
        {
            get { return debugMode; }
            set { debugMode = value; }
        }

        public bool RenderToIndexer
        {
            get { return renderToIndexer; }
            set { renderToIndexer = value; }
        }

        public bool InError
        {
            get
            {
                return inError;
            }
        }

        public void LogError(zsWebPartException Ex)
        {
            inError = true;
            if (errors == null) errors = new Collection<zsWebPartException>();

            errors.Add(Ex);
        }

        protected string GetToolPaneLink()
        {
            bool hasRights = ((ISecurableObject)SPContext.Current.Web).DoesUserHavePermissions((SPBasePermissions)Microsoft.SharePoint.SPPermissionGroup.WebDesigner);

            if (!hasRights)
                return "";

            string editLink = ToolPane.GetShowExtensibleToolPaneEvent(string.Format(@"'{0}'", this.UniqueID));
            editLink = string.Format(@"javascript:{0}", editLink.Replace(@"ExtensibleView", @"Edit"));
            return editLink;
        }

        protected override void RenderContents(System.Web.UI.HtmlTextWriter writer)
        {
            //Do not render if the user is the Indexer
            if (IsIndexer() && !renderToIndexer) return;

            //Render the error if it has occurred
            if (InError)
            {
                zsWebPartException firstError = errors[0];
                writer.Write(firstError.GetErrorMessage(debugMode));
                return;
            }

            //Render the web part
            try
            {
                base.RenderContents(writer);
            }
            catch (Exception exRender)
            {
                writer.Write(exRender.ToString());
            }
        }

        private static bool IsIndexer()
        {
            if (HttpContext.Current.Request.UserAgent != null)
            {
                if (HttpContext.Current.Request.UserAgent.Contains("MS Search 5.0 Robot"))
                {
                    return true;
                }
            }

            return false;
        }

        public string GetCacheKey(string Key, CacheScope CacheScope)
        {
            string cacheKey = "";
            switch (CacheScope)
            {
                case CacheScope.Page:
                    cacheKey = Key;
                    break;
                case CacheScope.WebPart:
                    cacheKey = ID + Key;
                    break;
                case CacheScope.User:
                    cacheKey = ID + Key + HttpContext.Current.User.Identity.Name;
                    break;
            }
            return cacheKey;
        }

        public object GetCachedObject(string CacheKey)
        {
            object cachedValue = null;
            HttpContext httpCtxt = HttpContext.Current;

            if (httpCtxt != null)
            {
                cachedValue = httpCtxt.Cache[CacheKey];
            }
            return cachedValue;
        }

        public void SetCachedObject(string CacheKey, object ObjectToCache, DateTime Expires, TimeSpan SlidingExpiration, bool RemoveOnEdit)
        {
            HttpContext httpCtxt = HttpContext.Current;

            if (httpCtxt != null)
            {
                httpCtxt.Cache.Insert(CacheKey, ObjectToCache, null, Expires, Cache.NoSlidingExpiration);
            }
        }

        public void RemoveCachedObject(string CacheKey)
        {
            HttpContext httpCtxt = HttpContext.Current;

            if (httpCtxt.Cache[CacheKey] != null)
                httpCtxt.Cache.Remove(CacheKey);
        }

        public void ClearCache()
        {
            HttpContext httpCtxt = HttpContext.Current;

            foreach (DictionaryEntry cacheEntry in httpCtxt.Cache)
            {
                string existingCacheKey = cacheEntry.Key.ToString();
                httpCtxt.Cache.Remove(existingCacheKey);
            }
        }

        protected override void OnEditModeChanged(EventArgs e)
        {
            ClearCache();

            base.OnEditModeChanged(e);
        }

    }
}